import axios from '@/api'
import { formatTree } from '@/utils/tools'

export interface IArea {
  s_up_id: string;
  s_a_id: string;
  s_a_nam: string;
  children?: Array<IArea>
}
export interface IGetAreaList {
  request: {
    usr_sfz: string;
    usr_psw: string;
  },
  response: Array<IArea>
}

class AreaServices {
  constructor() { }

  /**
   * 获取地区列表
   *
   * @returns
   * @memberof AreaServices
   */
  async getAreaList() {
    const res = await axios.post<unknown, Api.ResponseOptions<IGetAreaList['response']>>('/btsys/area/get-area-list')
    res.data = Object.freeze(formatTree(res.data, { id: 's_a_id', parentId: 's_up_id' }))
    return res
  }

  /**
   * 获取下级行政区数据
   *
   * @param {Pick<IArea, 's_a_id'>} data
   * @returns
   * @memberof AreaServices
   */
  async getAreaLazy(data: Pick<IArea, 's_a_id'>) {
    const res = await axios.post<unknown, Api.ResponseOptions<IGetAreaList['response']>>('/btsys/area/get-next-area', data)
    res.data = res.data.map(item => {
      if (item.s_a_nam) {
        return { ...item, hasChild: true }
      }
      return item
    })
    return res
  }

  /**
   * 编辑行政区
   *
   * @param {IArea} data
   * @returns
   * @memberof AreaServices
   */
  async editArea(data: IArea) {
    return await axios.post<unknown, Api.ResponseOptions>('/btsys/area/edit-area', data)
  }

  /**
   * 删除行政区
   *
   * @param {Pick<IArea, 's_a_id'>} data
   * @returns
   * @memberof AreaServices
   */
  async deleteArea(data: Pick<IArea, 's_a_id'>) {
    return await axios.post<unknown, Api.ResponseOptions>('/btsys/area/del-area', data)
  }
}

export const areaServices = new AreaServices()

export default AreaServices
